package com.lsfb.signln.Location.TaskMsg.Replenish.Signature;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.lsfb.signln.Index.IndexActivity;
import com.lsfb.signln.Location.SignIn.SignEvent;
import com.lsfb.signln.Login.LoginActivity;
import com.lsfb.signln.R;
import com.lsfb.signln.Utils.LittleUtils;
import com.lsfb.signln.Utils.URLString;
import com.lsfb.signln.View.SignNameView;
import com.zgscwjm.lsfbbasetemplate.Event.EventAnnotation;
import com.zgscwjm.lsfbbasetemplate.LsfbActivity;
import com.zgscwjm.lsfbbasetemplate.annotation.ContentView;
import com.zgscwjm.lsfbbasetemplate.annotation.OnClick;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInject;
import com.zgscwjm.lsfbbasetemplate.internet.BaseInternet;
import com.zgscwjm.lsfbbasetemplate.net.HttpClient;
import com.zgscwjm.lsfbbasetemplate.utils.DensityUtils;
import com.zgscwjm.lsfbbasetemplate.utils.LsfbLog;
import com.zgscwjm.lsfbbasetemplate.utils.T;
import com.zgscwjm.lsfbbasetemplate.view.titlebar.LsfbTitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 签名
 * Created by Administrator on 2018/1/25 0025.
 */
@ContentView(R.layout.aty_signature)
public class SignatureActivity extends LsfbActivity {

    @ViewInject(R.id.sign)
    private SignNameView sign;

    /**
     * 1第一次录入2人脸识别失败前面3审批前面
     */
    private String type;

    /**
     * 省市区行政编码
     */
    private String adcode;
    /**
     * 城市编码
     */
    private String citycode;
    /**
     * 参数校验值
     */
    private String token;


    @Override
    public void initView() {
        type = getIntent().getStringExtra("type");
        adcode = getIntent().getStringExtra("adcode");
        citycode = getIntent().getStringExtra("citycode");
        token = getIntent().getStringExtra("token");
        GetCAMEARPermission();

        LsfbTitleBar titleBar = LittleUtils.setsimpletitlebar(this, "签名");
        TextView textView = LittleUtils.rightbtn(this, "提交");

        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
            }
        });
        titleBar.setRightView(textView, 0, 0, DensityUtils.dp2px(this, 10), 0);
    }

    @Override
    public void initEvent() {

    }

    @OnClick({R.id.aty_signature_clean})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.aty_signature_clean:
                sign.clearPath();
                break;
        }
    }

    @Override
    public void initData() {

    }

    /**
     * 保存
     */
    public void save() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.CHINA);
        String fname = "/sdcard/" + sdf.format(new Date()) + ".png";
        sign.setDrawingCacheEnabled(true);
        sign.buildDrawingCache();
        Bitmap bitmap = sign.getDrawingCache();
        if (bitmap != null) {
            System.out.println("bitmap got !");
            try {
                FileOutputStream out = new FileOutputStream(fname);

                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                System.out.println("file " + fname + "output done.");
                LsfbLog.e("file " + fname + "output done." + "*****8989898989");
                File file = new File(fname);


                List<File> list = new ArrayList<>();
                list.add(file);

                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("img", file.getPath());
                new HttpClient().postFile(URLString.UPLOAD, hashMap, list, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                        LsfbLog.e("上传签名失败" + e.getMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        LsfbLog.e("上传签名success");
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(response.body().string());
                            LsfbLog.e("上传签名结果" + jsonObject.toString());
                            if (jsonObject.getInt("code") == 200) {
                                LsfbLog.e("上传签名得到回调");
                                String img = jsonObject.getString("data");

                                //1第一次录入2人脸识别失败签名3审批签名
                                if (type.equals("1")) {
                                    signimg(img);
                                } else if (type.equals("2")) {
                                    sign(img);
                                } else if (type.equals("3")) {

                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            LsfbLog.e("bitmap is NULL!");
        }
    }


    public void GetCAMEARPermission() {

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    1);
        } else {
            Log.e("nonsense", "读写权限开启");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                    T.showShort(this, "请求权限成功");
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    T.showShort(this, "请求权限失败");
                }
                break;
        }
    }

    /**
     * 完成签名图片的上传(第一次录入)
     *
     * @param imgPath
     */
    public void signimg(String imgPath) {
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("imgPath", imgPath);
        new BaseInternet().getData(URLString.SIGNIMG, hashMap, String.class, new SignatureEvent(), true);
    }

    @EventAnnotation
    public void SignatureEvent(SignatureEvent event) {
        switch (event.getCode()) {
            case 200:
                startActivity(new Intent(this, IndexActivity.class));
                break;
            case 1006:
                T.showShort(this, "您的账号已在其它设备登录，请重登录");
                LittleUtils.exit(this);
                startActivity(new Intent(this, LoginActivity.class));
                break;
            default:
                T.showShort(this, event.getMsg());
                break;
        }
    }

    /**
     * 签到，人脸签到失败，签名签到
     */
    public void sign(String signPath) {
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("cityCode", citycode);
        hashMap.put("adcode", adcode);
        hashMap.put("signType", "1");
        hashMap.put("signPath", signPath);
        hashMap.put("token", token);
        new BaseInternet().getData(URLString.SIGN, hashMap, String.class, new SignEvent(), true);
    }

    @EventAnnotation
    public void SignEvent(SignEvent event) {
        switch (event.getCode()) {
            case 200:
                T.showShort(this, "签到成功");
                finish();
                break;
            case 1006:
                T.showShort(this, "您的账号已在其它设备登录，请重登录");
                LittleUtils.exit(this);
                startActivity(new Intent(this, LoginActivity.class));
                break;
            default:
                T.showLong(this, event.getMsg());
//                finish();
                break;
        }
    }


}
